<template>
    <div class="register-modal" v-if="visible" @click.self="handleClose">
        <div class="modal-content">
            <!-- 左侧图片区域 -->
            <div class="modal-left">
                <img :src="modalLeftImg" alt="注册页面装饰图">
            </div>
            
            <!-- 右侧注册区域 -->
            <div class="modal-right">
                <div class="close-btn" @click="handleClose">
                    <svg-icon name="close" />
                </div>
                
                <div class="register-header">
                    <h2>注册账号</h2>
                    <p>加入我们，开启您的房产之旅</p>
                </div>

                <form class="register-form" @submit.prevent="onSubmit">
                    <div class="form-item">
                        <svg-icon name="user" class="input-icon" />
                        <input
                            type="text"
                            v-model="formData.username"
                            placeholder="请输入用户名"
                            :class="{ 'error': errors.username }"
                        >
                        <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
                    </div>

                    <div class="form-item">
                        <svg-icon name="phone" class="input-icon" />
                        <input
                            type="text"
                            v-model="formData.phone"
                            placeholder="请输入手机号"
                            :class="{ 'error': errors.phone }"
                        >
                        <span class="error-message" v-if="errors.phone">{{ errors.phone }}</span>
                    </div>
                    
                    <div class="form-item">
                        <svg-icon name="email" class="input-icon" />
                        <input
                            type="email"
                            v-model="formData.email"
                            placeholder="请输入邮箱(选填)"
                            :class="{ 'error': errors.email }"
                        >
                        <span class="error-message" v-if="errors.email">{{ errors.email }}</span>
                    </div>

                    <div class="form-item">
                        <svg-icon name="lock" class="input-icon" />
                        <input
                            :type="showPassword ? 'text' : 'password'"
                            v-model="formData.password"
                            placeholder="请输入密码"
                            :class="{ 'error': errors.password }"
                        >
                        <svg-icon
                            :name="showPassword ? 'eye-open' : 'eye-close'"
                            class="toggle-password"
                            @click="showPassword = !showPassword"
                        />
                        <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
                    </div>

                    <div class="form-item">
                        <svg-icon name="lock" class="input-icon" />
                        <input
                            :type="showConfirmPassword ? 'text' : 'password'"
                            v-model="formData.confirmPassword"
                            placeholder="请确认密码"
                            :class="{ 'error': errors.confirmPassword }"
                        >
                        <svg-icon
                            :name="showConfirmPassword ? 'eye-open' : 'eye-close'"
                            class="toggle-password"
                            @click="showConfirmPassword = !showConfirmPassword"
                        />
                        <span class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
                    </div>

                    <div class="form-item captcha-item">
                        <svg-icon name="verify" class="input-icon" />
                        <input
                            type="text"
                            v-model="formData.captcha"
                            placeholder="请输入图形验证码"
                            :class="{ 'error': errors.captcha }"
                            @focus="handleCaptchaFocus"
                        >
                        <img 
                            v-if="captchaImg"
                            :src="'data:image/png;base64,' + captchaImg" 
                            class="captcha-image" 
                            alt="图形验证码"
                            @click="refreshCaptcha"
                            @error="handleCaptchaError"
                        >
                        <div v-if="!captchaImg" class="captcha-placeholder" @click="refreshCaptcha">
                            点击获取验证码
                        </div>
                        <span class="error-message" v-if="errors.captcha">{{ errors.captcha }}</span>
                    </div>

                    <button type="submit" class="submit-btn" :disabled="loading">
                        {{ loading ? '注册中...' : '注册' }}
                    </button>

                    <div class="form-footer">
                        <span>已有账号？</span>
                        <a href="#" class="login-link" @click.prevent="showLogin">立即登录</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import { getCaptcha, register } from '@/api/user'
import { ElMessage } from 'element-plus'
import modalLeftImg from '@/assets/images/modal-left.jpeg'

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:visible'])

const userStore = useUserStore()
const loginStore = useLoginStore()

const showPassword = ref(false)
const showConfirmPassword = ref(false)
const loading = ref(false)
const captchaImg = ref('')
const captchaUrl = ref('/captcha?t=' + Date.now())
const debugMode = ref(true)
const captchaDebugInfo = ref('')

const formData = reactive({
    username: '',
    phone: '',
    email: '',
    password: '',
    confirmPassword: '',
    captcha: '',
    uuid: ''
})

const errors = reactive({
    username: '',
    phone: '',
    email: '',
    password: '',
    confirmPassword: '',
    captcha: ''
})

// 处理验证码加载错误
const handleCaptchaError = (e) => {
    console.error('验证码图片加载失败:', e)
    captchaDebugInfo.value = '图片加载失败: ' + e.target.src
    captchaImg.value = '' // 清空验证码图片，显示占位符
    // 尝试重新获取验证码
    setTimeout(() => {
        refreshCaptcha()
    }, 1000)
}

// 获取图形验证码
const refreshCaptcha = async () => {
    try {
        console.log('获取图形验证码，请求路径：/captcha')
        const res = await getCaptcha()
        console.log('图形验证码响应:', res)
        if (res.code === 200) {
            const { img, uuid } = res.data
            captchaImg.value = img
            formData.uuid = uuid
            formData.captcha = ''
            errors.captcha = ''
            console.log('图形验证码成功获取 - UUID:', uuid.substring(0, 8) + '...')
        } else {
            console.error('获取图形验证码失败，错误码:', res.code, '错误信息:', res.msg)
            errors.captcha = '获取验证码失败，请点击刷新'
        }
    } catch (error) {
        console.error('获取图形验证码异常:', error)
        errors.captcha = '获取验证码失败，请点击刷新'
    }
}

// 监听visible变化，当显示时刷新验证码
watch(() => props.visible, (newVal) => {
    if (newVal) {
        refreshCaptcha()
    }
})

// 组件挂载时获取验证码
onMounted(() => {
    if (props.visible) {
        refreshCaptcha()
    }
})

// 验证码输入框获取焦点时处理
const handleCaptchaFocus = () => {
    if (errors.captcha) {
        errors.captcha = ''
        refreshCaptcha()  // 只在用户主动聚焦时刷新验证码
    }
}

// 表单验证
const validateForm = () => {
    let isValid = true
    errors.username = ''
    errors.phone = ''
    errors.email = ''
    errors.password = ''
    errors.confirmPassword = ''
    errors.captcha = ''

    // 用户名校验
    if (!formData.username) {
        errors.username = '请输入用户名'
        isValid = false
    } else if (!/^[a-zA-Z0-9_]{4,16}$/.test(formData.username)) {
        errors.username = '用户名必须是4-16位字母、数字或下划线'
        isValid = false
    }

    // 手机号校验
    if (!formData.phone) {
        errors.phone = '请输入手机号'
        isValid = false
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
        errors.phone = '手机号格式不正确'
        isValid = false
    }

    // 邮箱校验
    if (!formData.email) {
        errors.email = '请输入邮箱'
        isValid = false
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        errors.email = '邮箱格式不正确'
        isValid = false
    }

    // 密码校验 - 使用更严格的规则
    if (!formData.password) {
        errors.password = '请输入密码'
        isValid = false
    } else if (formData.password.length < 8 || formData.password.length > 16) {
        errors.password = '密码长度必须在8-16个字符之间'
        isValid = false
    } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/.test(formData.password)) {
        errors.password = '密码必须包含大小写字母和数字'
        isValid = false
    }

    // 确认密码校验
    if (!formData.confirmPassword) {
        errors.confirmPassword = '请确认密码'
        isValid = false
    } else if (formData.confirmPassword !== formData.password) {
        errors.confirmPassword = '两次密码不一致'
        isValid = false
    }

    // 验证码校验
    if (!formData.captcha) {
        errors.captcha = '请输入图形验证码'
        isValid = false
    } else if (formData.captcha.length < 4) {
        errors.captcha = '验证码长度不正确'
        isValid = false
    }

    return isValid
}

// 提交注册
const onSubmit = async () => {
    if (!validateForm()) return

    try {
        loading.value = true
        const registerData = {
            username: formData.username,
            password: formData.password,
            confirmPassword: formData.confirmPassword,
            nickName: formData.username,
            realName: formData.username,
            phone: formData.phone,
            email: formData.email || '',
            sex: '0',
            code: formData.captcha,
            uuid: formData.uuid,
            registerSource: '1'
        }
        
        // 检查关键字段是否符合后端要求
        console.log('注册字段检查:')
        console.log('- 用户名:', registerData.username, '长度:', registerData.username.length)
        console.log('- 手机号:', registerData.phone, '是否符合格式:', /^1[3-9]\d{9}$/.test(registerData.phone))
        console.log('- 邮箱:', registerData.email)
        console.log('- 图形验证码:', registerData.code, '长度:', registerData.code.length)
        console.log('- UUID:', registerData.uuid ? registerData.uuid.substring(0, 8) + '...' : 'undefined')
        
        if (!formData.uuid) {
            console.error('图形验证码UUID不存在，尝试重新获取验证码')
            await refreshCaptcha()
            
            if (!formData.uuid) {
                ElMessage.error('无法获取验证码，请刷新页面后重试')
                loading.value = false
                return
            }
        }
        
        // 确保图形验证码字段正确
        console.log('提交注册请求:')
        console.log('- API URL:', '/system/user/register')
        console.log('- 验证码:', formData.captcha)
        console.log('- UUID:', formData.uuid ? formData.uuid.substring(0, 8) + '...' : 'undefined')
        
        // 直接使用API的register函数
        const result = await register({
            username: formData.username,
            password: formData.password,
            confirmPassword: formData.confirmPassword,
            nickName: formData.username,
            phone: formData.phone,
            email: formData.email || '',
            code: formData.captcha, // 图形验证码值
            uuid: formData.uuid     // 图形验证码UUID
        })
        
        console.log('注册结果:', result)
        
        if (result.code === 200) {
            // 注册成功后关闭弹窗并打开登录窗口
            ElMessage.success('注册成功')
            console.log('注册成功，用户名:', formData.username)
            
            // 如果注册时直接登录（后端返回了token）
            if (result.data && result.data.token) {
                console.log('注册时获取到token，自动登录')
                // 保存用户数据到store
                userStore.setUserInfo(result.data.user)
                emit('update:visible', false)
                
                // 延迟1秒后刷新页面，确保数据保存后刷新
                setTimeout(() => {
                    window.location.reload()
                }, 1000)
            } else {
                // 否则关闭注册窗口并打开登录窗口
                emit('update:visible', false)
                loginStore.showLogin()
            }
        } else {
            // 处理具体错误字段
            console.error('注册失败，错误代码:', result.code)
            console.error('错误信息:', result.msg)
            
            if (result.msg) {
                if (result.msg.includes('用户名')) {
                    errors.username = result.msg
                } else if (result.msg.includes('手机号')) {
                    errors.phone = result.msg
                } else if (result.msg.includes('邮箱')) {
                    errors.email = result.msg
                } else if (result.msg.includes('密码')) {
                    errors.password = result.msg
                } else if (result.msg.includes('验证码')) {
                    errors.captcha = result.msg
                    refreshCaptcha()
                } else {
                    // 显示通用错误
                    ElMessage.error(result.msg || '注册失败，请稍后重试')
                }
            } else {
                ElMessage.error('注册失败，请稍后重试')
            }
        }
    } catch (error) {
        console.error('注册失败，捕获到异常:', error)
        
        // 尝试提取更多错误信息
        if (error.response) {
            console.error('HTTP状态码:', error.response.status)
            console.error('响应数据:', error.response.data)
        }
        
        if (error.msg) {
            const errorMsg = error.msg
            console.error('错误消息:', errorMsg)
            
            if (errorMsg.includes('用户名')) {
                errors.username = errorMsg
            } else if (errorMsg.includes('手机号')) {
                errors.phone = errorMsg
            } else if (errorMsg.includes('邮箱')) {
                errors.email = errorMsg
            } else if (errorMsg.includes('密码')) {
                errors.password = errorMsg
            } else if (errorMsg.includes('验证码')) {
                errors.captcha = errorMsg
                refreshCaptcha()
            } else {
                // 显示通用错误
                ElMessage.error(errorMsg || '注册失败，请稍后重试')
            }
        } else if (error.message) {
            console.error('错误消息:', error.message)
            ElMessage.error(error.message || '注册失败，未知错误')
        } else {
            ElMessage.error('注册失败，未知错误')
        }
    } finally {
        loading.value = false
    }
}

// 显示登录弹窗
const showLogin = () => {
    emit('update:visible', false)
    loginStore.showLogin()
}

// 关闭弹窗
const handleClose = () => {
    emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.register-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .modal-content {
        display: flex;
        background: #fff;
        border-radius: 8px;
        overflow: hidden;
        width: 800px;
        max-width: 90%;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        .modal-left {
            width: 400px;
            flex-shrink: 0;
            background: #f5f7fa;
            display: flex;
            align-items: center;
            justify-content: center;
            
            img {
                max-width: 80%;
                max-height: 80%;
            }
        }

        .modal-right {
            position: relative;
            width: 400px;
            flex-shrink: 0;
            padding: 40px;
            box-sizing: border-box;

            .close-btn {
                position: absolute;
                top: 16px;
                right: 16px;
                cursor: pointer;
                padding: 8px;
                
                .svg-icon {
                    width: 20px;
                    height: 20px;
                    color: #999;
                    transition: color 0.3s;
                }

                &:hover .svg-icon {
                    color: #333;
                }
            }

            .register-header {
                text-align: center;
                margin-bottom: 40px;

                h2 {
                    font-size: 24px;
                    color: #333;
                    margin-bottom: 8px;
                }

                p {
                    font-size: 14px;
                    color: #999;
                }
            }

            .register-form {
                max-width: 320px;
                margin: 0 auto;
                width: 100%;
                
                .form-item {
                    position: relative;
                    margin-bottom: 24px;
                    width: 100%;

                    .input-icon {
                        position: absolute;
                        left: 12px;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 20px;
                        height: 20px;
                        color: #999;
                        pointer-events: none;
                    }

                    input {
                        width: 100%;
                        height: 44px;
                        padding: 0 12px 0 40px;
                        border: 1px solid #ddd;
                        border-radius: 4px;
                        font-size: 14px;
                        color: #333;
                        box-sizing: border-box;
                        transition: all 0.3s;

                        &::placeholder {
                            color: #999;
                            font-size: 14px;
                        }

                        &:focus {
                            border-color: #4A60A1;
                            box-shadow: 0 0 0 2px rgba(74, 96, 161, 0.1);
                            outline: none;
                        }

                        &.error {
                            border-color: #ff4d4f;
                            background-color: #fff2f0;
                        }
                    }

                    .toggle-password {
                        position: absolute;
                        right: 12px;
                        top: 50%;
                        transform: translateY(-50%);
                        width: 20px;
                        height: 20px;
                        color: #999;
                        cursor: pointer;
                        transition: color 0.3s;

                        &:hover {
                            color: #333;
                        }
                    }

                    .error-message {
                        position: absolute;
                        left: 0;
                        bottom: -20px;
                        display: flex;
                        align-items: center;
                        gap: 4px;
                        font-size: 12px;
                        color: #ff4d4f;
                        line-height: 1.5;
                    }

                    &.captcha-item {
                        input {
                            padding-right: 100px;
                        }

                        .captcha-image {
                            position: absolute;
                            right: 12px;
                            top: 50%;
                            transform: translateY(-50%);
                            height: 32px;
                            cursor: pointer;
                            border-radius: 4px;
                        }
                    }
                }

                .submit-btn {
                    width: 100%;
                    height: 44px;
                    background: #4A60A1;
                    border: none;
                    border-radius: 4px;
                    color: #fff;
                    font-size: 16px;
                    cursor: pointer;
                    transition: background 0.3s;

                    &:hover {
                        background: color.adjust(#4A60A1, $lightness: -5%);
                    }

                    &:disabled {
                        background: #ccc;
                        cursor: not-allowed;
                    }
                }

                .form-footer {
                    margin-top: 16px;
                    text-align: center;
                    font-size: 14px;
                    color: #666;

                    .login-link {
                        color: #4A60A1;
                        text-decoration: none;
                        margin-left: 4px;
                        transition: color 0.3s;

                        &:hover {
                            color: color.adjust(#4A60A1, $lightness: -10%);
                        }
                    }
                }
            }
        }
    }
}

// 添加响应式布局
@media screen and (max-width: 768px) {
    .register-modal .modal-content {
        flex-direction: column;
        width: 100%;
        max-width: 400px;
        margin: 20px;
        
        .modal-left {
            display: none;
        }
        
        .modal-right {
            width: 100%;
            padding: 30px 20px;
        }
    }
}

.captcha-placeholder {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    height: 32px;
    line-height: 32px;
    padding: 0 10px;
    background: #f1f1f1;
    color: #999;
    font-size: 12px;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
    
    &:hover {
        background: #e1e1e1;
        color: #666;
    }
}
</style> 